//
//  AccountViewModel.swift
//  lixiangweibo
//
//  Created by dyy on 15/11/28.
//  Copyright © 2015年 lixianggongzuoshi. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD

class AccountViewModel: NSObject {
    
    
    var account: UserAccount?
    override init() {
        account = UserAccount.loadAccount()
        
    }
    
    var userLogin: Bool {
    
    return account?.access_token != nil
    }
    var token: String?{
    
    return account?.access_token
        
    }
    var userName: String?{
    
    return account?.name
    }
    
    var headerImageUrl: NSURL?{
    
    let url = NSURL(string: account?.avatar_large ?? "")
        
        return url
    
    }

    func loadAccessToken(code: String,finish:(error: NSError?) ->()){
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let AFN = AFHTTPSessionManager()
        AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
        let parameters = ["client_id": client_id,"client_secret": client_secret,"grant_type": "authorization_code","code": code,"redirect_uri": redirect_uri]
        
        AFN.POST(urlString, parameters: parameters, success: { (_ , result) -> Void in
            /*
            "access_token" = "2.00R68kSG5YWFtD44704fe89a0Gc3K_";
            "expires_in" = 157679999;
            "remind_in" = 157679999;
            uid = 5773839483;
            */
            
            guard let dict = result as? [String: AnyObject] else {
                return
            }
            let account = UserAccount(dict: dict)
            
            self.userAccountInfo(account,finish:finish)
            
            }) { (_, error) -> Void in
                
                finish(error: error)
                print(error)
        }
        
        
    }
    
    private func userAccountInfo(account: UserAccount,finish:(error: NSError?) ->()){
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        let AFN = AFHTTPSessionManager()
        guard let access_token = account.access_token,uidId = account.uid else {
//            SVProgressHUD.showErrorWithStatus("网络不稳,无法访问")
            return
        }
        let parameters = ["access_token": access_token,"uid": uidId]
        AFN.GET(urlString, parameters: parameters, success: { (_, result) -> Void in
            account.name = result["name"] as? String
            account.avatar_large = result["avatar_large"] as? String
           // SVProgressHUD.showSuccessWithStatus("你可以玩了")
            account.saveAccount()
            finish(error: nil)
            
            }) { (_, error) -> Void in
                finish(error: error)
                print(error)
        }
    }

}
